package com.zydl.f9164m.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.BleLog;
import com.clj.fastble.utils.HexUtil;
import com.suke.widget.SwitchButton;
import com.zydl.f9164m.R;
import com.zydl.f9164m.basis.BasisFragment;
import com.zydl.f9164m.basis.Constants;
import com.zydl.f9164m.bean.ParamListData;
import com.zydl.f9164m.eventbus.FragmentChangeMessage;
import com.zydl.f9164m.eventbus.PopHandleMessage;
import com.zydl.f9164m.util.CountDown;
import com.zydl.f9164m.util.EditTextUtil;
import com.zydl.f9164m.util.SoftKeyBoardListener;
import com.zydl.f9164m.util.SubstringUtil;
import com.zydl.f9164m.view.PopHandle;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import my.BleUtils;
import my.CheckUtils;
import my.LogUtil;

public class LoraFragment extends BasisFragment {

    static LoraFragment fragment;

    public static LoraFragment newInstance() {
        if(fragment == null){
            fragment = new LoraFragment();
        }
        return fragment;
    }

    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    MyAdapter adapter;
    ArrayList<ParamListData> terminalList;
    ArrayList<ParamListData> originalList;
    public static int SUBMIT = 75;
    private boolean isFinish = false;

    private CountDown mCountDownTimer;
    private static final long MAX_TIME = 11 * 1000;
    private StringBuffer saveResult = new StringBuffer();
    private PopHandle popHandle;
    private int subPosition = 0;
    private Handler submitHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 75://75提交
                    isFinish = false;
                    if (subPosition < terminalList.size()) {
                        initSettingSaveThred(subPosition);
                        subPosition++;
                    } else {
                        BleUtils.stopNotify();
                        isFinish = true;
                        originalList.clear();
                        originalList = JSON.parseObject(JSON.toJSONString(terminalList),new TypeReference<ArrayList<ParamListData>>(){}); // Json 转List
                        dismissProgress();
                        mCountDownTimer.cancel();
                        if(!TextUtils.isEmpty(saveResult.toString())){
                            if (popHandle == null) {
                                popHandle = new PopHandle(mContext, "tips_fail", "错误信息", saveResult.toString());
                            }
                            popHandle.show();
                        }else {
                            showToast("保存成功");
                        }
                    }
                    break;
                case 76:  //检查是否传输完毕
                    try {
                        if(!isFinish && !getActivity().isFinishing()){
                            showToast("设置失败，请重试");
                            dismissProgress();
                            BleUtils.stopNotify();
                        }
                    }catch (NullPointerException e){
                        throw e;
                    }
                    break;
            }

        }
    };

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            LogUtil.d("终端fragment显示");
        } else {
            //相当于OnPause()
            LogUtil.d("终端fragment隐藏");
        }
    }

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.fragment_terminal);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);
        initCountDownTimer();
    }

    public void initCountDownTimer() {
        mCountDownTimer = new CountDown();
        mCountDownTimer.setMillisInFuture(MAX_TIME);
        mCountDownTimer.setCountdownInterval(1000);
        mCountDownTimer.setCountDownListener(new CountDown.CountDownListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onFinish() {
                submitHandler.sendEmptyMessage(Constants.CHECK_FINISH);
                //这时候可以做30秒的计时操作
        }

            @Override
            public void onTick(long millisUntilFinished) {
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        terminalList = new ArrayList<>();
        originalList = new ArrayList<>();
    }

    private boolean isEnable = false;
    public void setList(String sMsgObjString,int type) {
        terminalList.clear();
        isEnable = false;
        if (!TextUtils.isEmpty(sMsgObjString)) {

            if(sMsgObjString.indexOf("LORA") != -1){
                isEnable = true;
            }

            //设备ID
            String LoRaVer = SubstringUtil.subString(sMsgObjString, "LoRa ver:");
            terminalList.add(new ParamListData("LoRa版本号", 2, ""+LoRaVer, "", "",isEnable));


            //设备ID
            String LoRaID = SubstringUtil.subString(sMsgObjString, "LoRa NID:");
            terminalList.add(new ParamListData("ID", 2, ""+LoRaID, "AT+LNID", "(0-65535)",isEnable));

            //空中速率
            String LoRaLRS = SubstringUtil.subString(sMsgObjString, "LoRa LRS:");
            List<String> LoRaLRSList = Arrays.asList(getResources().getStringArray(R.array.number));
            terminalList.add(new ParamListData("速率", 1, "" + LoRaLRS, LoRaLRSList, "AT+LLRS",isEnable));

//            //工作模式
//            String LoRaMod = SubstringUtil.subString(sMsgObjString, "LoRa MOD:");
//            List<String> LoRaModList = Arrays.asList(getResources().getStringArray(R.array.loraMode));
//            terminalList.add(new ParamListData("工作模式", 1, "" + LoRaModList.get(Integer.valueOf(LoRaMod)), LoRaModList, "AT+LMOD",isEnable));

            //透传地址
            String LoRaTID = SubstringUtil.subString(sMsgObjString, "LoRa TID:");
            terminalList.add(new ParamListData("透传地址", 2, ""+LoRaTID, "AT+LTID", "(0-65535)",isEnable));

            //发射功率
            String LoRaTPR = SubstringUtil.subString(sMsgObjString, "LoRa TPR:");
            terminalList.add(new ParamListData("发射功率", 2, ""+LoRaTPR, "AT+LTPR", "(5-20)",isEnable));

            //载波频率
            String LoRaLFR = SubstringUtil.subString(sMsgObjString, "LoRa LFR:");
            terminalList.add(new ParamListData("载波频率(410-441 | 470-510 | 850-950)", 2, ""+LoRaLFR, "AT+LLFR", "",isEnable));

            //前导码周期时间
            String LoRaPPT = SubstringUtil.subString(sMsgObjString, "LoRa PPT:");
            terminalList.add(new ParamListData("前导码周期时间", 2, ""+LoRaPPT, "AT+LPPT", "(0-5s)",isEnable));

            //网络号
            String LoRaPID = SubstringUtil.subString(sMsgObjString, "LoRa PID:");
            terminalList.add(new ParamListData("网络号", 2, ""+LoRaPID, "AT+LPID", "(0-65535)",isEnable));

            //节点类型
            String LoRaTYP = SubstringUtil.subString(sMsgObjString, "LoRa TYP:");
            List<String> LoRaTYPList = Arrays.asList(getResources().getStringArray(R.array.loraType));
            terminalList.add(new ParamListData("节点类型", 1, "" + LoRaTYPList.get(Integer.valueOf(LoRaTYP)-1), LoRaTYPList, "AT+LTYP",isEnable));




            if(type == Constants.AT_FROM_DEVICE){
//                ArrayList<ParamListData> n = (ArrayList<ParamListData>) JSON.parseArray(a,ParamListData.class); // Json 转List
                originalList = JSON.parseObject(JSON.toJSONString(terminalList),new TypeReference<ArrayList<ParamListData>>(){}); // Json 转List
            }
        }

        adapter.notifyDataSetChanged();
        recyclerView.setAdapter(adapter);
    }

    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

        public MyAdapter() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_pass_way_base_item, viewGroup, false);
            return new ViewHolder(view);
        }


        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            viewHolder.list_item.setTag(position);
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return terminalList == null ? 0 : terminalList.size();
        }


        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {

            @BindView(R.id.list_item)
            LinearLayout list_item;
            @BindView(R.id.tv_name)
            TextView tvName;
            @BindView(R.id.edit_text)
            EditText editText;
            @BindView(R.id.img_spanner)
            ImageView imgSpanner;
            @BindView(R.id.tv_unit)
            TextView tvUnit;
            @BindView(R.id.tv_synchro)
            TextView tvSynchro;
            @BindView(R.id.switch_btn)
            SwitchButton switchBtn;

            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
                EditTextUtil.setEditTextNoEmoji(editText);
            }

            public void bind(int position) {
                ParamListData terminalListData = terminalList.get(position);
                tvName.setText(terminalListData.getName());
                switch (terminalListData.getType()) {
                    case 1: //spinner
                        editText.setText("" + (TextUtils.isEmpty(terminalListData.getValue()) ? terminalListData.getKey() : terminalListData.getValue()));
                        editText.setHint("请选择" + terminalListData.getName());
                        editText.setEnabled(terminalListData.isEnable());
                        imgSpanner.setVisibility(View.VISIBLE);
                        tvUnit.setVisibility(View.GONE);
                        switchBtn.setVisibility(View.GONE);
                        tvSynchro.setVisibility(View.GONE);

                        list_item.setBackgroundResource(R.color.white);
                        break;
                    case 2:  // edit
                        editText.setText("" + terminalListData.getValue());
                        editText.setHint("请输入" + terminalListData.getName());
                        editText.setEnabled(terminalListData.isEnable());
                        editText.setVisibility(View.VISIBLE);
                        tvUnit.setVisibility(View.VISIBLE);
                        tvUnit.setText(terminalListData.getUnit());
                        imgSpanner.setVisibility(View.GONE);
                        switchBtn.setVisibility(View.GONE);
                        tvSynchro.setVisibility(View.GONE);
                        list_item.setBackgroundResource(R.color.white);
                        break;
                }
                editText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        int curPosition = getAdapterPosition();
                        ParamListData data = terminalList.get(curPosition);
                        data.setValue(s.toString());
                    }
                });

                imgSpanner.setTag(terminalListData);
                tvSynchro.setTag(terminalListData);
            }

            @OnClick(R.id.img_spanner)
            public void showSpanner(View v) {
                SoftKeyBoardListener.hideKeyboard(getActivity());
                final ParamListData terminalListData = (ParamListData) v.getTag();
                OptionsPickerView pickerView = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        editText.setText(terminalListData.getValues().get(options1));
                    }
                })
                        .setSubmitText("确定")//确定按钮文字
                        .setCancelText("取消")//取消按钮文字
                        .build();
                pickerView.setPicker(terminalListData.getValues());
                pickerView.show();
            }
        }
    }

     StringBuffer atShowResult = new StringBuffer();
    @OnClick(R.id.btn_save)
    public void save() {
        atShowResult.setLength(0);
        showLoading();
        BleUtils.notify(mContext,new BleNotifyCallback() {
            @Override
            public void onNotifySuccess() {
                saveResult.setLength(0);
                subPosition = 0;
                submitHandler.sendEmptyMessage(Constants.SUBMIT);
            }

            @Override
            public void onNotifyFailure(BleException exception) {
                BleLog.d("下发设置打开通知操作失败");
            }

            @Override
            public void onNotifyFailure(String message) {
                showToast(message);
                dismissProgress();
            }

            @Override
            public void onCharacteristicChanged(byte[] data) {
                for (Byte a : data) {
                    atShowResult.append(String.format("%02X", a));
                }
                String sMes = HexUtil.hexStringToString(atShowResult.toString());
                if (sMes.contains("OK")) {
                    originalList.set(subPosition - 1, terminalList.get(subPosition - 1));
                    atShowResult.setLength(0);
                    submitHandler.sendEmptyMessage(Constants.SUBMIT);
                }else if(sMes.contains("ERROR")){
                    atShowResult.setLength(0);
                    onError();
                }
            }

            @Override
            public void onError() {
                saveResult.append(terminalList.get(subPosition-1).getName() + "保存失败"+"\r\n");
                submitHandler.sendEmptyMessage(Constants.SUBMIT);
            }

            @Override
            public void onReconSuc(String message) {
                dismissProgress();
                showToast(message);
            }
        });
    }

    public void initSettingSaveThred(final int position) {
        String url = getBlueToothUrl(terminalList.get(position));
        if (TextUtils.isEmpty(url)) {
//            showToast(terminalList.get(position).getName()+"的值不能为空");
//            dismissProgress();
            submitHandler.sendEmptyMessage(Constants.SUBMIT);
            return;
        }
        String originalurl = getBlueToothUrl(originalList.get(position));
        if (TextUtils.isEmpty(originalurl)) {
            originalurl = "";
        }
        if(originalurl.equals(url)){
            submitHandler.sendEmptyMessage(Constants.SUBMIT);
            return;
        }

        final String toSet = url;
        BleUtils.write(toSet, new BleWriteCallback() {
            @Override
            public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {
                if (current == total) {
                    mCountDownTimer.start();
                }
            }

            @Override
            public void onWriteFailure(final BleException exception) {
                saveResult.append(terminalList.get(position).getName() + "保存失败"+"\r\n");
            }
        });


    }

    private String getBlueToothUrl(ParamListData data) {
        String url;
        String name = data.getName();
        String at = data.getAction();
        String value = (data.getValue() == null)?data.getKey():data.getValue();
        if(TextUtils.isEmpty(value) || "数据异常，请重新获取".equals(value)){
//            return null;
            value="";
        }

        if(data.getName().equals("工作模式")){
            switch (value){
                case "TRNS":
                    value = "0";
                    break;
                case "PRO":
                    value = "1";
                    break;
            }
        }

        if(data.getName().equals("节点类型")){
            switch (value){
                case "路由器":
                    value = "1";
                    break;
                case "终端":
                    value = "2";
                    break;
            }
        }

        String a = HexUtil.strToHex((at + "=" + value));
        if (CheckUtils.isContansChinese(value)) {
            try {
                value = HexUtil.chineseWordToGbk(value);
                a = HexUtil.strToHexNoSpace((at + "=")) + value + "0D0A";
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return url = a;
    }


    @Override
    public void onMessageEvent(FragmentChangeMessage event) {
        super.onMessageEvent(event);
        BleLog.d("FragmentChangeMessage=lora="+event.message);
    }
}
